﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace ParkingYunService
{
    public partial class FrmServer : Form
    {
        string iptxt = null;
        int Port = 0;
        public FrmServer()
        {
            InitializeComponent();
            InitSysLog();
            chkServerRun.Checked = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["ServerRun"].ToString());
            iptxt = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString().Trim();
            Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ServerPort"].ToString().Trim());
            txtServerIp.Text = iptxt;
            txtServerPort.Text = Port.ToString();
            InitData();
            InitDB();
            this.tabPage1.Parent = null;

            InitSysFee();


        }
        //concrrentDirctory
        static AsyncSocketTCPServer openServer = null;
        //static Dictionary<string, System.Net.Sockets.Socket> DicList = new Dictionary<string, System.Net.Sockets.Socket>();
        static Dictionary<string, SocketList> DicListData = new Dictionary<string, SocketList>();
        // System.Threading.Thread th_pre = new System.Threading.Thread(inItZhuDongSend) { Name = "inItZhuDongSend", IsBackground = true };
        #region 连接
        /// <summary>
        /// 开启Socket
        /// </summary>
        private void OpenServer()
        {

            if (iptxt.Length == 0 && Port == 0)
            {
                MessageBox.Show("确保IP与端口正确", "提示", MessageBoxButtons.OK);
                return;
            }
            openServer = new AsyncSocketTCPServer(IPAddress.Parse(iptxt), Port, 1024);
            try
            {
                openServer.Start();
            }
            catch (Exception ex)
            {
                string str = "";
                string strDateInfo = "开启服务出现未处理的异常：" + DateTime.Now.ToString() + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                LogManage.WriteLog("出现应用程序未处理的异常", str);
                MessageBox.Show("开启失败:IP" + iptxt, "提示", MessageBoxButtons.OK);

                return;
            }
            //连接
            openServer.ClientConnected += openServer_ClientConnected;
            openServer.ClientDisconnected += openServer_ClientDisconnected;
            //接收数据
            openServer.DataReceived += openServer_DataReceived;
            //发送数据
            openServer.PrepareSend += openServer_PrepareSend;
            openServer.CompletedSend += openServer_CompletedSend;
            //异常
            openServer.NetError += openServer_NetError;
            openServer.OtherException += openServer_OtherException;
            btnOpenServer.Enabled = false;
            InitSend();
            MessageBox.Show("已经开启服务", "提示", MessageBoxButtons.OK);
            //  th_pre.Start();

        }

        /// <summary>
        /// 与客户端的连接已建立事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_ClientConnected(object sender, AsyncSocketEventArgs e) { }
        /// <summary>
        /// 与客户端的连接已断开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_ClientDisconnected(object sender, AsyncSocketEventArgs e) { }
        #endregion

        #region 接收数据
        /// <summary>
        /// 接收的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_DataReceived(object sender, AsyncSocketEventArgs e)
        {
            try
            {
                string IpAndPort = e._state.ClientSocket.RemoteEndPoint.ToString();
                byte[] buffer = e._state.RecvDataBuffer;
                string code = "";
                //接收数据后处理数据并发数据
                byte[] byteArray = SendDatas.beiDongSendData(IpAndPort, buffer, ref code);
                //if (code.Length > 0)
                //{
                //    if (!DicList.ContainsKey(code))
                //    {
                //        DicList.Add(code, e._state.ClientSocket);
                //        DataDisplay();
                //    }
                //}
                if (code.Length > 0)
                {
                    if (!DicListData.ContainsKey(code))
                    {
                        DicListData.Add(code, new SocketList() { soc = e._state.ClientSocket, time = DateTime.Now });
                    }
                    else
                    {
                        DicListData[code].time = DateTime.Now;
                    }
                    DataDisplay();
                }
                if (byteArray != null)
                {
                    openServer.Send(e._state, byteArray);
                    //  LogManage.WriteReceive(IpAndPort+"                   "+ System.Text.Encoding.UTF8.GetString(buffer));
                    //string msg = System.Text.Encoding.UTF8.GetString(byteArray);
                    //  LogManage.WriteSend(IpAndPort + "                   " + msg);
                }

            }
            catch (Exception ex)
            {
                string str = "";
                string strDateInfo = "接收的数据出现未处理的异常：" + DateTime.Now.ToString() + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                LogManage.WriteLog("出现应用程序未处理的异常", str);
            }
        }
        #endregion

        #region 发送数据时触发
        /// <summary>
        /// 发送数据前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_PrepareSend(object sender, AsyncSocketEventArgs e) { }
        /// <summary>
        /// 数据发送完毕事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_CompletedSend(object sender, AsyncSocketEventArgs e) { }
        #endregion

        #region 异常时触发
        /// <summary>
        /// 网络错误事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_NetError(object sender, AsyncSocketEventArgs e) { }
        /// <summary>
        /// 异常事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_OtherException(object sender, AsyncSocketEventArgs e)
        {
            LogManage.WriteLog("程序异常");
        }
        #endregion

        #region 系统设置
        /// <summary>
        /// 开机启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkServerRun_CheckedChanged(object sender, EventArgs e)
        {
            string R_startPath = Application.ExecutablePath;
            if (chkServerRun.Checked == true)
            {
                try
                {
                    EditAppConfig("ServerRun", "true");
                    RegistryKey R_local = Registry.LocalMachine;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue("WindowsServer", R_startPath);
                    R_run.Close();
                    R_local.Close();
                }
                catch (Exception ex)
                {
                    LogManage.WriteLog("开机是否启动", "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace);
                    EditAppConfig("ServerRun", "false");

                    MessageBox.Show("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
            }
            else
            {
                try
                {
                    EditAppConfig("ServerRun", "false");

                    RegistryKey R_local = Registry.LocalMachine;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue("WindowsServer", false);
                    R_run.Close();
                    R_local.Close();
                }
                catch (Exception ex)
                {
                    LogManage.WriteLog("开机是否启动", "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace);
                    EditAppConfig("ServerRun", "true");

                    MessageBox.Show("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            }
        }
        /// <summary>
        /// 用于操作App.config
        /// </summary>
        string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "ParkingYunService.exe.config";
        /// <summary>
        /// 修改config 
        /// 其中它是不能直接修改健值的，是在修改之前要删除该键值，然后重新添加。
        ///同是，上面的只是对AppSettings进行操作，其实也可以对ConnectionStrings、SectionGroups、Sections进行操作。
        /// </summary>
        /// <param name="Key"></param>
        protected void EditAppConfig(string strKey, string strValue)
        {
            try
            {

                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                //找出名称为“add”的所有元素
                XmlNodeList nodes = doc.GetElementsByTagName("add");
                for (int i = 0; i < nodes.Count; i++)
                {
                    //获得将当前元素的key属性
                    XmlAttribute att = nodes[i].Attributes["key"];
                    //根据元素的第一个属性来判断当前的元素是不是目标元素
                    if (att.Value == "" + strKey + "")
                    {
                        //对目标元素中的第二个属性赋值
                        att = nodes[i].Attributes["value"];
                        att.Value = strValue;
                        break;
                    }
                }
                //保存上面的修改
                doc.Save(path);
            }
            catch (Exception ex)
            {
                LogManage.WriteLog("修改config ", "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace);
                throw ex;
            }

        }
        /// <summary>
        /// 数据备份设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDataBack_CheckedChanged(object sender, EventArgs e)
        {

            try
            {
                string R_startPath = Application.ExecutablePath;
                if (chkDataBack.Checked == true)
                {
                    EditAppConfig("DataBack", "true");

                }
                else
                {

                    EditAppConfig("DataBack", "false");

                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void InitDB()
        {
            string myConnect = new GlobalClass().GetConnectionStringsConfig("DefaultConnection");
            string[] arycon = myConnect.Split(';');
            int i, li_index;
            for (i = 0; i < arycon.Length; i++)
            {
                if (arycon[i].IndexOf("Data Source") > -1)
                {
                    li_index = arycon[i].IndexOf("=");
                    this.txtServerAddress.Text = arycon[i].Substring(li_index + 1);
                }
                if (arycon[i].IndexOf("Initial Catalog") > -1)
                {
                    li_index = arycon[i].IndexOf("=");
                    this.txtName.Text = arycon[i].Substring(li_index + 1);
                }
                if (arycon[i].IndexOf("User ID") > -1)
                {
                    li_index = arycon[i].IndexOf("=");
                    this.txtUserName.Text = arycon[i].Substring(li_index + 1);
                }
                if (arycon[i].IndexOf("Password") > -1)
                {
                    li_index = arycon[i].IndexOf("=");
                    this.txtPsd.Text = arycon[i].Substring(li_index + 1);
                }
            }
        }
        /// <summary>
        /// 保存数据库连接串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveServer_Click(object sender, EventArgs e)
        {
            string strServerAddress = txtServerAddress.Text.Trim();
            string strName = txtName.Text.Trim();
            string strUserName = txtUserName.Text.Trim();
            string strPsd = txtPsd.Text.Trim();
            if (strServerAddress == "" || strName == "" || strUserName == "")
            {
                System.Windows.Forms.MessageBox.Show("数据库连接信息未填写完整！", "提示");
            }
            else
            {
                string strCon = "Data Source=" + txtServerAddress.Text.Trim() + ";Initial Catalog=" + txtName.Text.Trim() + ";Persist Security Info=True;User ID=" + txtUserName.Text.Trim() + ";Password=" + txtPsd.Text.Trim() + ";Connect Timeout=10";
                new GlobalClass().UpdateConnectionStringsConfig("DefaultConnection", strCon, "System.Data.SqlClient");
                System.Windows.Forms.MessageBox.Show("数据库连接配置成功，请重启程序！", "提示");
                Application.Exit();
            }
        }
        #endregion

        #region 开关服务按钮事件
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenServer_Click(object sender, EventArgs e)
        {
            OpenServer();
            btnOpenServer.Enabled = false;
            btnSaveServer.Enabled = true;

        }
        /// <summary>
        /// 关闭服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetServer_Click(object sender, EventArgs e)
        {
            openServer.Stop();
            openServer = null;
            btnOpenServer.Enabled = true;
            btnSaveServer.Enabled = false;
            dataGridView1.Rows.Clear();
            // tSend.Stop();
            //th_pre.Abort();
            MessageBox.Show("已关闭服务", "提示", MessageBoxButtons.OK);
        }
        #endregion

        #region 数据日志和异常
        /// <summary>
        /// 写入系统日志的定时器
        /// </summary>
        public static System.Timers.Timer tLog = new System.Timers.Timer(60000);//实例化timer类，设置间隔时间为60000毫秒(1分钟)；
        /// <summary>
        /// 系统日志
        /// </summary>
        protected void InitSysLog()
        {

            tLog.Elapsed += new System.Timers.ElapsedEventHandler(TheTimeoutWriteSysLog);//到达时间的时候执行事件； 
            tLog.AutoReset = true;//设置是执行一次（false）还是一直执行(true)； 
            tLog.Enabled = true;//是否执行system.timers.timer.elapsed事件； 

        }
        /// <summary>
        /// 系统日志 加锁防止多线程同时访问一个文件造成IO异常
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void TheTimeoutWriteSysLog(object source, System.Timers.ElapsedEventArgs e)
        {
            //加锁状态，防止重复执行某一任务
            if (LogManage.Processing == false)
            {
                lock (LogManage.LockObject)
                {
                    if (LogManage.Processing == false)
                    {
                        LogManage.Processing = true;
                        LogManage.WriteLog();
                        DataDisplay();
                        LogManage.WriteReceive();
                        LogManage.WriteSend();
                        LogManage.Processing = false;
                    }
                }
            }
        }
        /// <summary>
        /// 日志查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogQuery_Click(object sender, EventArgs e)
        {
            string strdtpLogStart = dtpLogStart.Text;
            string strdtpLogEnd = dtpLogEnd.Text;

            lvLogFile.Items.Clear();
            if (strdtpLogStart == "" || strdtpLogEnd == "")
            {
                MessageBox.Show("请输入起止日期！", "提示");
            }
            else
            {
                DateTime dtStart = DateTime.Parse(strdtpLogStart);
                DateTime dtEnd = DateTime.Parse(strdtpLogEnd);
                string strFileName = "";
                if (dtStart <= dtEnd)
                {
                    DateTime dt = new DateTime();
                    int span = new TimeSpan(dtEnd.Ticks - dtStart.Ticks).Days + 1;
                    string R_startPath = Application.StartupPath;
                    string filePath = "";
                    for (int i = 0; i < span; i++)
                    {
                        dt = dtStart.AddDays(i);
                        strFileName = dt.ToString("yyyyMMdd") + "_log.txt";
                        filePath = R_startPath + "\\Logs\\" + strFileName;

                        if (File.Exists(filePath))
                        {
                            lvLogFile.Items.Add(strFileName);
                        }
                    }
                    //string R_startPath = Application.StartupPath;

                }
                else
                {
                    MessageBox.Show("开始日期必须大于等于结束日期！", "提示");
                }
            }
        }
        /// <summary>
        /// 查询数据日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            string strdtpStart = dateTimePicker2.Text;
            string strdtpEnd = dateTimePicker1.Text;
            string type = comboBox1.Text;
            lvDataFile.Items.Clear();
            if (strdtpStart == "" || strdtpEnd == "")
            {
                MessageBox.Show("请输入起止日期！", "提示");
                return;
            }

            if (type == "")
            {
                MessageBox.Show("请选择接收的数据或者发送的数据！", "提示");
                return;
            }
            DateTime dtStart = DateTime.Parse(strdtpStart);
            DateTime dtEnd = DateTime.Parse(strdtpEnd);
            string strFileName = "";
            if (dtStart <= dtEnd)
            {
                DateTime dt = new DateTime();
                int span = new TimeSpan(dtEnd.Ticks - dtStart.Ticks).Days + 1;
                string R_startPath = Application.StartupPath;
                string filePath = "";
                for (int i = 0; i < span; i++)
                {
                    dt = dtStart.AddDays(i);
                    strFileName = dt.ToString("yyyyMMdd") + ".txt";
                    filePath = R_startPath + (type == "接收" ? "\\ReceiveData\\" : "\\SendData\\") + strFileName;
                    if (File.Exists(filePath))
                    {
                        lvDataFile.Items.Add(strFileName);
                    }
                }
            }
            else
            {
                MessageBox.Show("开始日期必须大于等于结束日期！", "提示");
            }
        }
        private void lvLogFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                string R_startPath = Application.StartupPath;
                if (lvLogFile.SelectedItem != null)
                {
                    string strFileName = lvLogFile.SelectedItem.ToString();
                    string filePath = R_startPath + "\\Logs\\" + strFileName;
                    txtLog.Text = "";
                    if (File.Exists(filePath))
                    {
                        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        string s = "";
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            while ((s = sr.ReadLine()) != null)
                            {
                                txtLog.Text += s + "\r\n";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                LogManage.WriteLog("文件查看失败", "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace);
                MessageBox.Show("文件查看失败,失败原因为：" + "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace, "提示");

            }
            finally
            {

            }
        }
        private void lvDataFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string type = comboBox1.Text;
                if (type == "")
                {
                    MessageBox.Show("请选择接收的数据或者发送的数据！", "提示");
                    return;
                }
                string R_startPath = Application.StartupPath;
                if (lvDataFile.SelectedItem != null)
                {
                    string strFileName = lvDataFile.SelectedItem.ToString();
                    string filePath = R_startPath + (type == "接收" ? "\\ReceiveData\\" : "\\SendData\\") + strFileName;
                    textBox1.Text = "";
                    if (File.Exists(filePath))
                    {
                        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        string s = "";
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            while ((s = sr.ReadLine()) != null)
                            {
                                textBox1.Text += s + "\r\n";
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManage.WriteLog("文件查看失败", "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace);
                MessageBox.Show("文件查看失败,失败原因为：" + "Msg:" + ex.Message + "  StackTrace" + ex.StackTrace, "提示");

            }
            finally
            {

            }
        }
        #endregion

        private void btnSave_Click(object sender, EventArgs e)
        {
            string ip = txtServerIp.Text.Trim();
            string po = txtServerPort.Text.Trim();
            if (ip.Length == 0 && po.Length == 0)
            {
                MessageBox.Show("确保IP与端口正确", "提示", MessageBoxButtons.OK);
                return;
            }
            EditAppConfig("ServerIP", ip);
            EditAppConfig("ServerOort", po);
            MessageBox.Show("保存成功请重启服务", "提示", MessageBoxButtons.OK);
        }

        private void InitData()
        {
            this.dataGridView1.Columns[0].HeaderCell.Value = "ID";
            this.dataGridView1.Columns[1].HeaderCell.Value = "设备名称";
            this.dataGridView1.Columns[2].HeaderCell.Value = "设备IP";
            this.dataGridView1.Columns[3].HeaderCell.Value = "物业名";
            this.dataGridView1.Columns[4].HeaderCell.Value = "停车场名";
            this.dataGridView1.Columns[5].HeaderCell.Value = "状态";
            this.dataGridView1.Columns[6].HeaderCell.Value = "连接时间";
        }
        private void DataDisplay()
        {
            this.Invoke(new Action(() =>
            {
                dataGridView1.Rows.Clear();
                InitData();
                foreach (var item in DicListData)
                {
                    var modelList = new WeChatParking.Core.BLL.Device().GetList(item.Key);
                    if (modelList != null && modelList.Count > 0)
                    {
                        foreach (var ditem in modelList)
                        {
                            ditem.Device_IP = item.Value.soc.RemoteEndPoint.ToString().Split(':')[0];

                            if (!(item.Value.time < DateTime.Now.AddMinutes(-2)))
                            {
                                ditem.version = 10;
                                this.dataGridView1.Rows.Add(ditem.ID, ditem.Device_name, ditem.Device_IP, ditem.Enterprise_name, ditem.TcEnterprise_name, "在线", item.Value.time);
                            }
                            else
                            {
                                ditem.version = 0;
                                this.dataGridView1.Rows.Add(ditem.ID, ditem.Device_name, ditem.Device_IP, ditem.Enterprise_name, ditem.TcEnterprise_name, "掉线", item.Value.time);
                            }
                            new WeChatParking.Core.BLL.Device().Update(ditem, "SERVER");
                        }
                    };
                }
            }));
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butSearch_Click(object sender, EventArgs e)
        {
            string name = txtSearch.Text.Trim();
            if (name.Length > 0)
            {
                var model = new WeChatParking.Core.BLL.Device().GetToName(name);

                if (DicListData.ContainsKey(model.DeviceClient_code))
                {
                    dataGridView1.Rows.Clear();
                    InitData();

                    this.dataGridView1.Rows.Add(model.ID, model.Device_name, model.Device_IP, model.Enterprise_name, model.TcEnterprise_name, "", DateTime.Now);
                }
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定要关闭服务？", "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                System.Environment.Exit(0);
            }
        }

        private void FrmServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Visible = false;
            notifyIcon1.Visible = true;
            e.Cancel = true;
        }

        private void FrmServer_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                notifyIcon1.Visible = true;
            }
            else
            {
                notifyIcon1.Visible = false;
            }
        }

        #region 主动发送定时器
        /// <summary>
        ///主动发送定时器
        /// </summary>
        public static System.Timers.Timer tSend = new System.Timers.Timer(3000);//实例化timer类，设置间隔时间为10000毫秒(5秒)；
        /// <summary>
        /// 主动发送
        /// </summary>
        protected void InitSend()
        {

            tSend.Elapsed += new System.Timers.ElapsedEventHandler(TheTimeDongSendData);//到达时间的时候执行事件； 
            tSend.AutoReset = true;//设置是执行一次（false）还是一直执行(true)； 
            tSend.Enabled = true;//是否执行system.timers.timer.elapsed事件；

        }
        protected void TheTimeDongSendData(object source, System.Timers.ElapsedEventArgs e)
        {
            this.YpaySendData();
            this.FeeQuerySendData();
        }
        /// <summary>
        /// 预缴费
        /// </summary>
        protected void YpaySendData()
        {
            try
            {
                string code = "";
                WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
                WeChatParking.Entity.Api.YPay ypay = bll.GetYPay(String.Format(" State=1 "), "create_time");
                byte[] dataByte = SendDatas.zhuDongYPay(ypay, ref code);
                if (dataByte != null && code.Length > 0)
                {
                    if (DicListData.ContainsKey(code))
                    {
                        if (DicListData[code] != null)
                        {
                            openServer.Send(DicListData[code].soc, dataByte);
                            bll.UpdateYPay(ypay.Guid, 2);
                        }
                    }
                }
            }
            catch (Exception e)
            {

                LogManage.WriteLog("数据库监听预缴费异常", e.ToString());
            }
        }
        /// <summary>
        /// 费用查询
        /// </summary>
        protected void FeeQuerySendData()
        {
            try
            {
                string code = "";
                WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
                WeChatParking.Entity.Api.FeeQuery feeQuery = bll.GetFeeQuery(String.Format(" State=1 "), "create_time");
                var dataByte = SendDatas.zhuDongFeeQuery(feeQuery, ref code);
                if (dataByte != null && code.Length > 0)
                {
                    if (DicListData.ContainsKey(code))
                    {
                        if (DicListData[code] != null)
                        {
                            openServer.Send(DicListData[code].soc, dataByte);
                            bll.UpdateFeeQuery(feeQuery.Guid, 2);
                        }
                    }
                }
            }
            catch (Exception e)
            {

                LogManage.WriteLog("数据库监听费用查询异常", e.ToString());
            }

        }
        #endregion

        private void button3_Click(object sender, EventArgs e)
        {
            string request = "";
            string Car_plate = textBox3.Text.Trim();
            var res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().carStatusQuery(Car_plate, out  request);
            WeChatParking.Core.LogHelper.Info(request, WeChatParking.Entity.Enums.LogType.UnionPay_carStatus);
            WeChatParking.Core.LogHelper.Info(res, "无感主动查询车辆状态请返回");
        }
        //进场
        private void button4_Click(object sender, EventArgs e)
        {
            string carBrand = textBox3.Text.Trim();
            WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
            bll.ServerAddIn(new WeChatParking.Entity.Api.InOrOut()
            {
                Car_plate = carBrand,
                Time = "201809061545",
                Type = 0,
                Car_type = 1,
                ImgLen = 100,
                CarUser_type = 1,
                Parking_code = "24566876fgdffs23",
                Guid = DateTime.Now.ToString()
            }, "1243.jpg");
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string carBrand = textBox3.Text.Trim();
            string request = "";
            var res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().noticeExit("100", carBrand, DateTime.Now.AddMinutes(-15), "3", "一指通停车场001", out request);
            WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
            bll.ServerAddOut(new WeChatParking.Entity.Api.InOrOut()
            {
                Car_plate = carBrand,
                Time = "201809061553",
                Type = 1,
                Car_type = 1,
                ImgLen = 100,
                CarUser_type = 1,
                Parking_code = "24566876fgdffs23",
                Guid = DateTime.Now.ToString()
            }, "1243.jpg");
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string carBrand = textBox3.Text.Trim();
            int Fee = int.Parse(textBox4.Text.Trim());
            WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
            bll.XCPay(new WeChatParking.Entity.Api.XCPay()
            {
                Parking_code = "24566876fgdffs23",
                Car_plate = carBrand,
                Fee = Fee,
                Time = "201809061545",

            });
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

        public static System.Timers.Timer tFee = new System.Timers.Timer(2000);//实例化timer类，设置间隔时间为60000毫秒(1分钟)；

        protected void InitSysFee()
        {

            tFee.Elapsed += new System.Timers.ElapsedEventHandler(TheTimeoutWriteSysFee);//到达时间的时候执行事件； 
            tFee.AutoReset = true;//设置是执行一次（false）还是一直执行(true)； 
            tFee.Enabled = true;//是否执行system.timers.timer.elapsed事件； 

        }
        protected void TheTimeoutWriteSysFee(object source, System.Timers.ElapsedEventArgs e)
        {
            WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
            bll.feeQuer();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            string orderID = textBox5.Text.Trim();
            string request = "";
            string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().payStatus(orderID, out request);
            WeChatParking.Core.LogHelper.Info(request, "无感主动支付订单查询");
            WeChatParking.Core.LogHelper.Info(res, "无感主动支付订单查询返回");
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            string request = "";
            string carBrand = textBox3.Text.Trim();
            string orderID = textBox5.Text.Trim();
            string upRefundId = textBox2.Text.Trim();
            int Fee = int.Parse(textBox4.Text.Trim());
            string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundBill(carBrand, Fee, upRefundId, orderID, out request);
            WeChatParking.Core.LogHelper.Info(request, "无感主动退款订单");
            WeChatParking.Core.LogHelper.Info(res, "无感主动退款订单返回");
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            string request = "";
            string upRefundId = textBox2.Text.Trim();
            string orderID = textBox5.Text.Trim();
            string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundStatus(orderID, upRefundId, out request);
            WeChatParking.Core.LogHelper.Info(request, "无感主动退款订单查询");
            WeChatParking.Core.LogHelper.Info(res, "无感主动退款订单查询返回");
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK);
        }

    }
}
